#include "fileparser.h"
#include "qdebug.h"
#include "qstringlist.h"
#include "qfile.h"

using namespace std;

FileParser::FileParser(){}

FileParser::~FileParser(void) {
}

template<typename TYPE>
bool FileParser::read(QString filename, TYPE &list) {
	if(filename == NULL) {
		qDebug() << "No filename entered";
		return false;
	}

	QFile file(filename);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return false;

    QTextStream in(&file);

	while(!in.atEnd()) { 
		QString line = in.readLine();
		if(!parseFromString(list, line))
			qDebug() << line;
	}

	file.close();

	return true;
}

//explicit declaration of possible template types
template bool FileParser::read<QList<AirportEntry*>>(QString filename, QList<AirportEntry*> &list);
template bool FileParser::read<QList<RouteEntry*>>(QString filename, QList<RouteEntry*> &list);

bool FileParser::parseFromString(QList<AirportEntry*> &list, QString line) {
	line.remove(QChar('"'));

	QStringList splitString = line.split(",");	

	bool ok;
	if(splitString.size() != 11) { 
		qDebug() << "Wrong number of arguments in line";
		return false;
	}

	int id			= splitString[0].toInt(&ok);
	QString name	= splitString[1];
	QString city	= splitString[2];
	QString country = splitString[3];
	QString iata	= splitString[4];
	QString icao	= splitString[5];
	double lat		= splitString[6].toDouble(&ok);
	double lon		= splitString[7].toDouble(&ok);
	double alt		= splitString[8].toDouble(&ok);
	double timez	= splitString[9].toDouble(&ok);
	QString dst		= splitString[10];

	if(!ok) { 
		qDebug() << "Something wrong in argument conversion";
		return false;
	}
	
	list.append(new AirportEntry(id, name, city, country, iata, icao, lat, lon, alt, timez, dst));

	//if(list.size() % 100 == 0) //for debugging purposes
	//	qDebug() << list.last()->toString();

	return true;
}


bool FileParser::parseFromString(QList<RouteEntry*> &list, QString line) {
	line.remove(QChar('"'));

	QStringList splitString = line.split(",");	

	bool ok;
	if(splitString.size() != 9) { 
		qDebug() << "Wrong number of arguments in line";
		return false;
	}

	QString airline		= splitString[0];
	int airline_ID		= splitString[1].toInt(&ok);
	QString origin		= splitString[2];
	int origin_ID		= splitString[3].toInt(&ok);
	QString dest		= splitString[4];
	int dest_ID			= splitString[5].toInt(&ok);
	QString codeshare	= splitString[6];
	int stops			= splitString[7].toInt(&ok);
	QString equipment	= splitString[8];


	if(!ok) { 
		qDebug() << "Something wrong in argument conversion";
		return false;
	}

	list.append(new RouteEntry(airline, airline_ID, origin, origin_ID, dest, dest_ID, codeshare, stops, equipment));
	
	//if(list.size() % 100 == 0) //for debugging purposes
	//	qDebug() << list.last()->toString();
	
	return true;
}